package com.df.happylearn.articles;

import com.android.volley.VolleyError;
import com.df.happylearn.model.ArticleInfo;
import com.df.happylearn.request.DataProvider;
import com.df.happylearn.sqlite.DBUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by dingfeng on 2016/5/24.
 */
public class ArticlesPresenter implements ArticlesContract.Presenter {

    private final ArticlesContract.View mArticlesView;
    public final static int limit = 15;
    private int offset = 0;

    public ArticlesPresenter(ArticlesContract.View articlesView) {
        mArticlesView = articlesView;
        mArticlesView.setPresenter(this);
    }

    @Override
    public void start() {
        loadArticles();
    }

    @Override
    public void loadArticles() {
        offset = 0;
        DataProvider.getInstance().getArticleList(2, 0, limit, new DataProvider.Callback<ArrayList<ArticleInfo>>() {
            @Override
            public void onSuccess(ArrayList<ArticleInfo> data) {
                DBUtil.getInstance().getArticleDao().savaOrUpdate(data);// save to db
                List<ArticleInfo> list = DBUtil.getInstance().getArticleDao().queryAll(offset, limit, "ctime", false);
                if (list != null) {
                    offset = offset + list.size();
                    mArticlesView.showArticles(list);
                } else {
                    mArticlesView.showNoArticles();
                }
            }

            @Override
            public void onError(VolleyError error) {
                // get data from db
                List<ArticleInfo> list = DBUtil.getInstance().getArticleDao().queryAll(offset, limit, "ctime", false);
                if (list != null && list.size() > 0) {
                    offset = offset + list.size();
                    mArticlesView.showArticles(list);
                } else {
                    mArticlesView.showNoArticles();
                }

            }
        });
    }

    @Override
    public void loadArticles(final int page) {
        DataProvider.getInstance().getArticleList(2, page, limit, new DataProvider.Callback<ArrayList<ArticleInfo>>() {
            @Override
            public void onSuccess(ArrayList<ArticleInfo> data) {
                DBUtil.getInstance().getArticleDao().savaOrUpdate(data);// save to db
                List<ArticleInfo> list = DBUtil.getInstance().getArticleDao().queryAll(offset, limit, "ctime", false);
                if (list != null) {
                    offset = offset + list.size();
                    mArticlesView.showMore(list);
                }
            }

            @Override
            public void onError(VolleyError error) {

            }
        });
    }

}
